package com.mxnavi5.example.DataStream;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.time.temporal.TemporalUnit;
import java.util.Iterator;

public class MyEventTimeTest {

    private static final OutputTag<Tuple2<Integer,Integer>> outputTag = new OutputTag<Tuple2<Integer,Integer>>("OutputTag") {
    };


    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        env.setParallelism(1);
//        Integer[] array = new Integer[]{1000, 1000, 2000, 3000, 11000, 4000, 13000, 5000, 19000, 9000,22000};
        SingleOutputStreamOperator integerDataStreamSource = env.addSource(new UdfSourceTest3()).returns(Integer.class);
        SingleOutputStreamOperator<Integer> integerSingleOutputStreamOperator =
                integerDataStreamSource.assignTimestampsAndWatermarks(
//                        WatermarkStrategy.<Integer>forMonotonousTimestamps()
                      WatermarkStrategy.<Integer>forBoundedOutOfOrderness(Duration.ofMillis(100))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Integer>() {

                            @Override
                            public long extractTimestamp(Integer element, long recordTimestamp) {
                                return element;
                            }
                        }));

        SingleOutputStreamOperator<Tuple2<Integer, Integer>> processStream = integerSingleOutputStreamOperator.process(new ProcessFunction<Integer, Tuple2<Integer, Integer>>() {
            @Override
            public void processElement(Integer value, ProcessFunction<Integer, Tuple2<Integer, Integer>>.Context ctx, Collector<Tuple2<Integer, Integer>> out) throws Exception {
                out.collect(Tuple2.of(1,value));
//                System.out.println("currentValue:"+value+",currentWatermark:"+ctx.timerService().currentWatermark());
            }
        });


        SingleOutputStreamOperator<String> process = processStream.keyBy(x -> x.f0).window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .allowedLateness(Time.seconds(5))
                .sideOutputLateData(outputTag)
                .process(new ProcessWindowFunction<Tuple2<Integer, Integer>, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer integer, ProcessWindowFunction<Tuple2<Integer, Integer>, String, Integer, TimeWindow>.Context context, Iterable<Tuple2<Integer, Integer>> iterable, Collector<String> collector) throws Exception {
                        Integer res = 0;
                        Iterator<Tuple2<Integer, Integer>> iterator = iterable.iterator();
                        while (iterator.hasNext()) {
                            Integer i = iterator.next().f1;
                            res += i;
                            System.out.println("windowMessage,value:"+i+",window:"+context.window().getStart()+"---"
                                    +context.window().getEnd()+",currentWatermark:" +context.currentWatermark());
                        }
                        collector.collect("window:"+context.window().getStart()+"---"+context.window().getEnd() +
                                ",currentWatermark:" +context.currentWatermark()+",result:"+res);
                    }
                });

        process.print("res:::::::::");
        process.getSideOutput(outputTag).print("OutputLateData");

        env.execute();

    }
}
